/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <sf-form ref="form"
             class="add-algorithm__form"
             :label-width="100">
        <div class="form__type">
            <div class="form__title">
                <lang>基础信息</lang>
            </div>
            <sf-form-item>
                <sf-fieldlabel>
                    <lang>算法名称</lang>
                </sf-fieldlabel>
                <sf-textfield
                    ref="fieldName"
                    v-model="submitData.name"
                    :default-width="defaultWidth"
                    :max-length="30"
                    :allow-blank="false"
                    :utf8-length="false"
                    vtype="name"
                    :blur-trim="true"
                    :placeholder="_('请输入算法名称')" />
            </sf-form-item>
             <sf-form-item class="flex-center">
                <sf-fieldlabel>
                    <lang>类别</lang>
                </sf-fieldlabel>
                 <sf-radio-group 
                v-model="submitData.type">
                <sf-radio 
                    name="type"
                    :check-value="0">
                    算法文件
                </sf-radio>
                </sf-radio-group>
             </sf-form-item>
            <sf-form-item>
                <sf-fieldlabel>
                    <lang>描述</lang>
                </sf-fieldlabel>
                <sf-textarea
                    v-model="submitData.description"
                    :placeholder="_('最多300字（选填）')"
                    :default-width="defaultWidth"
                    :max-length="300"
                    :utf8-length="false" />
            </sf-form-item>
            <div v-if="!isEdit">
                <div class="form__title">
                    <lang>算法文件配置</lang>
                </div>
                <sf-form-item>
                    <sf-fieldlabel class="p-l0">
                        <lang>选择算法文件</lang>
                    </sf-fieldlabel>
                    <sf-textfield
                        ref="uploadTextField"
                        v-model="submitData.file"
                        :default-width="265"
                        :placeholder="_('请选择算法文件')"
                        :allow-blank="false"
                        :default-disabled="true" />
                    <sf-fileupload
                        ref="fileUpload"
                        class="sfv-btn-primary"
                        :url="fileURL"
                        :params="submitData"
                        :accept="acceptFile"
                        :auto-upload="false"
                        @progress="handleProgress"
                        @change="_selectFile"
                        @uploadfile:failure="uploadFailure"
                        @uploadfile:success="uploadSuccess">
                        <lang>选择</lang>
                    </sf-fileupload>
                </sf-form-item>
                <div class="uploadFile__tips">
                    <span>{{ acceptFileText }}</span>
                </div>
                <sf-form-item>
                    <sf-fieldlabel class="p-l0">
                        <lang>算法标签</lang>
                    </sf-fieldlabel>
                    <sf-select v-model="submitData.tags"
                        :options="aiHubTagList"
                        searchable
                        type="multi"
                        :default-width="defaultWidth"
                        :allow-blank="true"
                        placeholder="请选择算法类型"
                        :select-limit="5"
                            :select-limit-text="_('最多允许选择5项')"
                            />
                </sf-form-item>
            </div>
        </div>
    </sf-form>
</template>
<script>
const DEFAULT_WIDTH = 352;
const DEFAULT_VALUE = {
    name: '',
    description: '',
    fileMd5:'',
    file:'',
    type:0,
    tags:[]
};
const MAX_SIZE = 2147483648; // 2GB
import store from 'src/vuex/store';
let userID = store.state.userId;

const ACEEPT_TYPE = ['.zip', '.rar'];
import SparkMD5 from 'spark-md5';

import AIHUBLIST from './algorithm';
import trainingUrlAdapter from 'src/home/mod_common/training_url_adapter';

export default{
    computed:{
        defaultWidth () {
            return DEFAULT_WIDTH;
        },
        acceptFile () {
           return ACEEPT_TYPE.join(',');
        },
        acceptFileText () {
            return _('支持扩展名：{0}，上传文件可能较慢，请耐心等候', ACEEPT_TYPE.join(' '));
        },
        fileURL () {
            return trainingUrlAdapter(`user/${userID}/aiHub/file`);
        }
    },
    data(){
        return {
            isEdit: false,
            submitData: { ...DEFAULT_VALUE },
            isDisabledField: false,
            progress: 0,
            algorithmTypeId: 0,
            aiHubTagList:AIHUBLIST,
        }
    },
    methods:{
        getJsonValue () {
            return this.submitData;
        },
        setJsonValue (data) {
            Object.assign(this.submitData, data);
        },
        _selectFile (files) {
            let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
            let file =  files[0];
            /* eslint-disable */
            let chunkSize = MAX_SIZE;                             // Read in chunks of 2MB
            let chunks = Math.ceil(file.size / chunkSize);
            let currentChunk = 0;
            let vm = this;
            let spark = new SparkMD5.ArrayBuffer();
            let fileReader = new FileReader();
            this.$mask();
            if (!/.zip|.rar$/.test(file.name)) {
                vm.$showErr(_('只支持上传{0}文件', vm.acceptFile));
                return false;
            }
            if (file.size > MAX_SIZE) {
                vm.$showErr(_('上传文件的体积应小于2GB'));
                return false;
            }
            fileReader.onload = function (e) {
                // @ts-ignore
                spark.append(e.target.result);                   // Append array buffer
                currentChunk++;
                if (currentChunk < chunks) {
                    loadNext();
                } else {
                    vm.$unmask();
                    vm.submitData.file = file.name;
                    vm.submitData.fileMd5 = spark.end();
                }
            };

            fileReader.onerror = function () {
                vm.$unmask();
                vm.$showErr(_('上传失败'));
            };

            function loadNext() {
                let start = currentChunk * chunkSize,
                    end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;

                fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
            }

            loadNext();
        },
        uploadSuccess (vm, result, file, jsonData) {
            this.$parent.options.uploadSuccessCallback(jsonData);
        },

        uploadFailure (vm, result, file, jsonData) {
            this.$refs.fileUpload.progressWindow && this.$refs.fileUpload.progressWindow.hide(); // 隐藏进度条
            this.$parent.options.uploadFailureCallback(jsonData);
        },

        handleProgress (loaded, total) {
            this.progress = loaded / total;
        },

        beginUpload () {
            let uploader = this.$refs.fileUpload;
            if (uploader) {
                uploader.uploadFile();
            }
        }
    },
}
</script>
<style lang="less" >
.add-algorithm__form {
    padding:10px 32px;
  .model-tips {
    background-color: #fdf3e4;
    color: #e0720b;
    padding: 10px;
    margin-bottom: 10px;
    text-align: center;
  }
  .alert__content{
    width: 336px;
    text-align: left;
    border-bottom: none;
    margin-left: 102px;
    height: 60px;
    line-height: 21px;
    display: flex;
    padding: 0 10px;
    padding-top: 8px;
    .sfv-alert__title{
        max-width: 100%;
        margin: 0;
        margin-left:5px;
        text-overflow: ellipsis;
        white-space: inherit;
    }
  }
  .form__title{
    margin-bottom: 10px;
    margin-left: -8px;
    color: #14161a;
    font-weight: bold;
  }

  .label-form__tabel {
    border: none;
  }
  .uploadFile {
    display: flex;
    align-items: center;
    .sfv-btn-primary {
      margin-left: 8px;
    }
  }
  .uploadFile__tips {
    padding-left: 105px;
    margin-top: -8px;
    margin-bottom: 12px;
    color: #a3a3a3;
    .upload-download{
        color: #204ed9;
        margin-left: 108px;
    }
  }
}
</style>
